package com.project.config.interceptor;

import com.project.utils.result.ResultModel;
import com.project.utils.result.ResultTools;
import com.project.utils.token.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
  * @author : Mr.Yan
  * @create : 2020/6/22
  * @description : 全局异常
  */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

	// 监听无权限得异常
	@ExceptionHandler(value = AuthorizationException.class)
	@ResponseBody
	public ResultModel defaultErrorHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws Exception{
		log.info("权限异常");
		return ResultTools.fail("您没有此操作权限！");
	}

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(CustomException.class)
	@ResponseBody
	public ResultModel handleException(CustomException e) {
		// 打印异常信息
		log.error("### 异常信息:{} ###", e.getMessage());
		return e.getResultModel();
	}


	/**
	 * 处理所有不可知的异常
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ResultModel handleOtherException(Exception e){
		//打印异常堆栈信息
		e.printStackTrace();
		// 打印异常信息
		log.error("### 不可知的异常:{} ###", e.getMessage());
		return ResultTools.fail("不可知异常");
	}
    	/**
	 * 处理所有不可知的异常
	 */
	@ExceptionHandler(MaxUploadSizeExceededException.class)
	@ResponseBody
	public ResultModel handleMaxUploadSizeExceededException(MaxUploadSizeExceededException  e){
		//打印异常堆栈信息
		e.printStackTrace();
		// 打印异常信息
		log.error("### 上传文件过大:{} ###", e.getMessage());
		return ResultTools.fail("上传文件过大");
	}
}
